package com.caiyi.financial.nirvana.sms.gateway.sgip.message;

import com.caiyi.financial.nirvana.sms.gateway.sgip.SGIPHeader;
import io.netty.buffer.ByteBuf;

/**
 * SGIP消息定义
 *
 * @author zhu_tek
 */
public class SGIPMessage extends SGIPHeader implements Message, Cloneable {

    public static final int SGIP_BIND = 0x00000001; // BIND消息ID

    public static final int SGIP_BIND_RESP = 0x80000001; // BIND_RESP消息ID

    public static final int SGIP_UNBIND = 0x00000002; // UNBIND消息ID

    public static final int SGIP_UNBIND_RESP = 0x80000002; // UNBIND_RESP消息ID

    public static final int SGIP_SUBMIT = 0x00000003; // SUBMIT消息ID

    public static final int SGIP_SUBMIT_RESP = 0x80000003; // SUBMIT_RESP消息ID

    public static final int SGIP_DELIVER = 0x00000004; // DELIVER消息ID

    public static final int SGIP_DELIVER_RESP = 0x80000004; // DELIVER_RESP消息ID

    public static final int SGIP_REPORT = 0x00000005; // REPORT消息ID

    public static final int SGIP_REPORT_RESP = 0x80000005; // REPORT_RESP消息ID

    //空消息体
    protected SGIPBody body = SGIPBody.NOOP_BODY;
    private boolean decodeSuccess = true;

    public boolean isDecodeSuccess() {
        return decodeSuccess;
    }

    public void setDecodeSuccess(boolean decodeSuccess) {
        this.decodeSuccess = decodeSuccess;
    }

    /**
     * @return SGIPBody
     */
    public SGIPBody getBody() {
        return body;
    }

    /**
     * @param body
     */
    public void setBody(SGIPBody body) {
        this.body = body;
    }

    /***
     * 设置消息头
     * @param header
     */
    public void setHeader(SGIPHeader header) {
        this.totalLength = header.getTotalLength();
        this.commandID = header.getCommandID();
        this.spNodeNum = header.getSpNodeNum();
        this.timestamp = header.getTimestamp();
        this.sequenceId = header.getSequenceId();
    }

    /***
     * 消息编码
     */
    @Override
    public int encode(ByteBuf buffer) {
        int index = buffer.writerIndex();
        int size = super.encode(buffer);
        int bodySize = getBody().encode(buffer);
        size += bodySize;
        setTotalLength(size);
        buffer.setInt(index, size);
        return size;
    }

    /**
     * 消息解码
     */
    @Override
    public SGIPMessage decode(ByteBuf buffer) {
        super.decode(buffer);
        SGIPBody body = SGIPBody.createBody(super.getCommandID());
        body.decode(buffer);
        this.body = body;
        return this;
    }

    /**
     * clone
     */
    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
        }
        SGIPMessage message = new SGIPMessage();
        message.setHeader(this);
        message.setBody(getBody());
        return message;
    }

    /**
     *
     */
    @Override
    public String toString() {
        return getBody() + "COMMANID:" + Integer.toHexString(commandID) + " SEQ:" + sequenceId;
    }
}
